package com.wang.springbootinit.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.exception.ThrowUtils;
import com.wang.springbootinit.mapper.QuestionMapper;
import com.wang.springbootinit.model.dto.answer.SubmitAnswerRequest;
import com.wang.springbootinit.model.dto.question.QuestionAddRequest;
import com.wang.springbootinit.model.dto.question.QuestionUpdateRequest;
import com.wang.springbootinit.model.entity.*;
import com.wang.springbootinit.model.vo.AnswerAnalyzeDataVO;
import com.wang.springbootinit.model.vo.QuestionVO;
import com.wang.springbootinit.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;

/**
 * 题目管理
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private ResearchChapterService chapterService;

    @Autowired
    private ResearchSubjectService researchSubjectService;

    @Autowired
    private AnswerRecordService answerRecordService;

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;


    /**
     * 学生做题列表-学生分页获取题目
     * @param chapterId 章节id
     * @param questionType 题目类型
     * @param questionCategory 题目分类
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public Page<QuestionVO> getQuestionsByChapterPage(Long chapterId, Integer questionType,
                                                    Integer questionCategory, long current, long pageSize,HttpServletRequest request) {
        Student loginStudent = userService.getLoginStudent(request);

        // 创建查询条件构造器
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();

        // 添加必要的查询条件
        queryWrapper.eq(Question::getChapterId, chapterId);

        // 添加可选的查询条件
        if (questionType != null) {
            queryWrapper.eq(Question::getQuestionType, questionType);
        }
        if (questionCategory != null) {
            queryWrapper.eq(Question::getQuestionCategory, questionCategory);
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Question::getCreateTime);

        // 创建分页对象并执行查询
        Page<Question> questionPage = this.page(new Page<>(current, pageSize), queryWrapper);

        List<AnswerRecord> answerRecords = new ArrayList<>();
        List<Question> questionList = questionPage.getRecords();
        if(CollectionUtils.isNotEmpty(questionList)){
            List<Long> questionIds = questionList.stream().map(Question::getId).collect(Collectors.toList());
            LambdaQueryWrapper<AnswerRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AnswerRecord::getStudentId,loginStudent.getId());
            lambdaQueryWrapper.in(AnswerRecord::getQuestionId,questionIds);
            answerRecords = answerRecordService.list(lambdaQueryWrapper);
        }


        return convertStudentQuestionPageToVOPage(questionPage,answerRecords);
    }

    private Page<QuestionVO> convertStudentQuestionPageToVOPage(Page<Question> questionPage,List<AnswerRecord> answerRecords) {
        //fixme 这里转map可能有问题，一个学校做同样的题两次之后，就会出现问题了
        Map<Long, AnswerRecord> answerMap = answerRecords.stream().collect(toMap(AnswerRecord::getQuestionId, Function.identity(), (answer1, answer2) -> answer1));
        Page<QuestionVO> voPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        List<QuestionVO> voList = questionPage.getRecords().stream()
                .map(item -> convertToVO(item,answerMap))
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    private QuestionVO convertToVO(Question question,Map<Long, AnswerRecord> answerMap) {
        QuestionVO questionVO = new QuestionVO();
        BeanUtils.copyProperties(question, questionVO);
        //判断学生是否做过这个题
        AnswerRecord answerRecord = answerMap.get(question.getId());
        if(ObjectUtil.isNotNull(answerRecord)){
            questionVO.setIsDone(true);
            questionVO.setIsCorrect(answerRecord.getIsCorrect());
        }else{
            questionVO.setIsDone(false);
        }
        return questionVO;
    }



    @Override
    public List<Question> getQuestionsByChapter(Long chapterId, Integer type, Integer category) {
        // 验证章节是否存在
        ResearchChapter chapter = chapterService.getById(chapterId);
        ThrowUtils.throwIf(ObjectUtil.isNull(chapter), ErrorCode.NOT_FOUND_ERROR, "章节不存在");

        // 构建查询条件
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Question::getChapterId, chapterId);
        if (ObjectUtil.isNotNull(type)) {
            queryWrapper.eq(Question::getQuestionType, type);
        }
        if (ObjectUtil.isNotNull(category)) {
            queryWrapper.eq(Question::getQuestionCategory, category);
        }

        return this.list(queryWrapper);
    }

    @Override
    public Boolean addQuestion(QuestionAddRequest questionAddRequest) {
        // 验证章节是否存在
        ResearchChapter chapter = chapterService.getById(questionAddRequest.getChapterId());
        ThrowUtils.throwIf(chapter == null, ErrorCode.NOT_FOUND_ERROR, "章节不存在");

        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        return this.save(question);
    }

    @Override
    public Boolean updateQuestion(QuestionUpdateRequest questionUpdateRequest) {
        // 验证题目是否存在
        Question oldQuestion = this.getById(questionUpdateRequest.getId());
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR, "题目不存在");

        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        return this.updateById(question);
    }

    /**
     * 学生提交答案
     * @param submitAnswerRequest 答案请求
     * @return
     */
    @Override
    public Boolean submitAnswers(SubmitAnswerRequest submitAnswerRequest, HttpServletRequest request) {
        Student loginStudent = userService.getLoginStudent(request);

        ResearchChapter chapter = chapterService.getById(submitAnswerRequest.getChapterId());
        if(ObjectUtil.isNull(chapter)){
            throw new BusinessException("章节信息不存在");
        }

        List<SubmitAnswerRequest.AnswerItem> answers = submitAnswerRequest.getAnswers();
        if(CollectionUtils.isEmpty(answers)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        List<Long> questionIds = answers.stream().map(SubmitAnswerRequest.AnswerItem::getQuestionId).collect(Collectors.toList());
        List<Question> questionList = listByIds(questionIds);
        Map<Long, Question> questionMap = questionList.stream().collect(toMap(Question::getId, Function.identity()));

        Map<Long, String> answerMap = answers.stream().collect(toMap(SubmitAnswerRequest.AnswerItem::getQuestionId, SubmitAnswerRequest.AnswerItem::getAnswer));


        List<AnswerRecord> answerRecords = answers.stream().map(item -> {
            AnswerRecord answerRecord = new AnswerRecord();

            Question question = questionMap.get(item.getQuestionId());
            if(question.getQuestionType() == 1){
                String answer = answerMap.get(item.getQuestionId());
                answerRecord.setIsCorrect(question.getAnswer().equals(answer));
            }

            answerRecord.setQuestionId(item.getQuestionId());
            answerRecord.setAnswerContent(item.getAnswer());
            answerRecord.setStudentId(loginStudent.getId());
            return answerRecord;
        }).collect(Collectors.toList());

        return answerRecordService.saveBatch(answerRecords);
    }

    /**
     * 获取章节下的所有题目
     * @param chapterId
     * @return
     */
    @Override
    public List<Question> getByChapterId(Long chapterId) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Question::getChapterId,chapterId);
        return list(queryWrapper);
    }

    @Override
    public List<QuestionVO> listVOByIds(List<Long> questionIds) {
        return new ArrayList<>();
    }


    /**
     * 教师端-分页获取题目答题数据情况
     * @param chapterId
     * @param questionType
     * @param questionCategory
     * @param questionId
     * @param current
     * @param pageSize
     * @param request
     * @return
     */
    @Override
    public Page<AnswerAnalyzeDataVO> getAnswerTestDataPage(Long chapterId, Integer questionType, Integer questionCategory, Integer questionId, long current, long pageSize, HttpServletRequest request) {
        // 创建查询条件构造器
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Question::getChapterId, chapterId);
        if (questionType != null) {
            queryWrapper.eq(Question::getQuestionType, questionType);
        }
        if (questionCategory != null) {
            queryWrapper.eq(Question::getQuestionCategory, questionCategory);
        }
        if( questionId != null){
            queryWrapper.eq(Question::getId,questionId);
        }
        queryWrapper.orderByDesc(Question::getCreateTime);
        Page<Question> questionPage = this.page(new Page<>(current, pageSize), queryWrapper);

        List<Question> questionList = questionPage.getRecords();
        if(CollectionUtils.isEmpty(questionList)){
            return new Page<>();
        }

        //章节和科目信息
        Map<Long, ResearchChapter> chapterHashMap = new HashMap<>();
        Map<Long, ResearchSubject> subjectHashMap = new HashMap<>();
        List<Long> chapterIds = questionList.stream().map(Question::getChapterId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(chapterIds)){
            List<ResearchChapter> chapterList = chapterService.listByIds(chapterIds);
            if(CollectionUtils.isNotEmpty(chapterList)){
                chapterHashMap = chapterList.stream().collect(toMap(ResearchChapter::getId, Function.identity(), (chapter1, chapter2) -> chapter1));

                List<Long> subjectIds = chapterList.stream().map(ResearchChapter::getSubjectId).collect(Collectors.toList());
                List<ResearchSubject> subjectList = researchSubjectService.listByIds(subjectIds);
                if(CollectionUtils.isNotEmpty(subjectList)){
                    subjectHashMap = subjectList.stream().collect(toMap(ResearchSubject::getId, Function.identity(), (subject1, subject2) -> subject1));
                }
            }
        }

        //答题记录数据
        List<Long> questionIds = questionList.stream().map(Question::getId).collect(Collectors.toList());
        List<AnswerRecord> answerRecords = answerRecordService.list(new LambdaQueryWrapper<AnswerRecord>()
                .in(AnswerRecord::getQuestionId,questionIds).eq(AnswerRecord::getIsDelete,0));
        if(CollectionUtils.isEmpty(answerRecords)){
            return convertQuestionPageToVOPage(questionPage);
        }

        //分组算出学生每个选项的正确率等
        Map<Long, List<AnswerRecord>> recordMap = answerRecords.stream().collect(groupingBy(AnswerRecord::getQuestionId));
        
        // 转换为VO对象
        Page<AnswerAnalyzeDataVO> voPage = new Page<>();
        Map<Long, ResearchChapter> finalChapterHashMap = chapterHashMap;
        Map<Long, ResearchSubject> finalSubjectHashMap = subjectHashMap;
        List<AnswerAnalyzeDataVO> analyzeDataVOS = questionList.stream().map(question -> {
            AnswerAnalyzeDataVO vo = new AnswerAnalyzeDataVO();
            // 复制基本题目信息
            vo.setQuestionId(question.getId());
            vo.setQuestionContent(question.getContent());
            vo.setQuestionAnalysis(question.getAnalysis());
            vo.setQuestionAnswer(question.getAnswer());
            vo.setQuestionType(question.getQuestionType());
            vo.setQuestionCategory(question.getQuestionCategory());
            ResearchChapter chapter = finalChapterHashMap.get(question.getChapterId());
            if(ObjectUtil.isNotNull(chapter)){
                vo.setChapterId(chapter.getId());
                vo.setChapterName(chapter.getChapterName());
                ResearchSubject subject = finalSubjectHashMap.get(chapter.getSubjectId());
                if(ObjectUtil.isNotNull(subject)){
                    vo.setSubjectId(subject.getId());
                    vo.setSubjectName(subject.getSubjectName());
                }
            }

            // 获取该题目的所有答题记录
            List<AnswerRecord> questionRecords = recordMap.getOrDefault(question.getId(), Collections.emptyList());
            if(CollectionUtils.isNotEmpty(questionRecords)){
                // 计算答题统计数据
                int totalAnswers = questionRecords.size();
                vo.setTotalAnswerCount(totalAnswers);

                // 计算正确答题数和正确率
                long correctCount = questionRecords.stream()
                        .filter(item ->ObjectUtil.isNotEmpty(item.getIsCorrect())&&item.getIsCorrect())
                        .count();
                double correctRate = (double) correctCount / totalAnswers * 100;
                vo.setTotalCorrectRate(String.format("%.2f%%", correctRate));

                if (totalAnswers > 0) {
                    //选择题情况
                    if(question.getQuestionType() == 1){
                        // 统计各个选项的选择次数
                        Map<String, Long> optionCounts = questionRecords.stream()
                                .collect(groupingBy(AnswerRecord::getAnswerContent, Collectors.counting()));

                        vo.setOptionACount(optionCounts.get("A"));
                        vo.setOptionBCount(optionCounts.get("B"));
                        vo.setOptionCCount(optionCounts.get("C"));
                        vo.setOptionDCount(optionCounts.get("D"));
                    }else{
                        //综合题情况
                        vo.setSynthesisRate(correctCount);
                    }

//                // 获取作答学生列表
//                List<StudentVO> studentVOs = questionRecords.stream()
//                    .map(record -> {
//                        StudentVO studentVO = new StudentVO();
//                        Student student = studentService.getById(record.getStudentId());
//                        if (student != null) {
//                            BeanUtils.copyProperties(student, studentVO);
//                        }
//                        return studentVO;
//                    })
//                    .collect(Collectors.toList());
//                vo.setAnsweredStudents(studentVOs);
                }
            }
            

            
            return vo;
        }).collect(Collectors.toList());

        // 设置分页信息
        voPage.setRecords(analyzeDataVOS);
        voPage.setSize(questionPage.getSize());
        voPage.setCurrent(questionPage.getCurrent());
        voPage.setTotal(questionPage.getTotal());
        
        return voPage;
    }


    //学生答题记录数据管理，答题记录为空的情况
    private Page<AnswerAnalyzeDataVO> convertQuestionPageToVOPage(Page<Question> questionPage) {
        List<Question> questionList = questionPage.getRecords();
        Page<AnswerAnalyzeDataVO> voPage = new Page<>();
        List<AnswerAnalyzeDataVO> analyzeDataVOS = questionList.stream().map(item -> {
            AnswerAnalyzeDataVO answerAnalyzeDataVO = new AnswerAnalyzeDataVO();
            answerAnalyzeDataVO.setQuestionId(item.getId());
            answerAnalyzeDataVO.setQuestionContent(item.getContent());
            answerAnalyzeDataVO.setQuestionAnalysis(item.getAnalysis());
            answerAnalyzeDataVO.setQuestionAnswer(item.getAnswer());
            answerAnalyzeDataVO.setQuestionType(item.getQuestionType());
            answerAnalyzeDataVO.setQuestionCategory(item.getQuestionCategory());
            return answerAnalyzeDataVO;
        }).collect(Collectors.toList());

        voPage.setRecords(analyzeDataVOS);
        voPage.setSize(questionPage.getSize());
        voPage.setCurrent(questionPage.getCurrent());
        voPage.setTotal(questionPage.getTotal());
        return voPage;
    }
}
